import { PageEnum } from '/@/enums/pageEnum'
import { unref } from 'vue'

import { REDIRECT_NAME } from '/@/router/constant'
import { useRouter } from '@/use/useVueApi'

export type PathAsPageEnum<T> = T extends { path: string } ? T & { path: PageEnum } : T
export type RouteLocationRawEx = PathAsPageEnum<any>

function handleError(e: Error) {
  console.error(e)
}

/**
 * page switch
 */
export function useGo(_router?: any) {
  const router = _router || useRouter()
  function go(opt: RouteLocationRawEx = PageEnum.BASE_HOME, isReplace = false) {
    if (!opt) {
      return
    }
    isReplace ? router.replace(opt).catch(handleError) : router.push(opt).catch(handleError)
  }
  return go
}

/**
 * @description: redo current page
 */
export const useRedo = (_router?: any) => {
  const router = _router || useRouter()
  const { query, params = {}, name, fullPath } = unref(router.currentRoute.value)
  function redo(): Promise<boolean> {
    return new Promise((resolve) => {
      if (name === REDIRECT_NAME) {
        resolve(false)
        return
      }
      if (name && Object.keys(params).length > 0) {
        params['_redirect_type'] = 'name'
        params['path'] = String(name)
      } else {
        params['_redirect_type'] = 'path'
        params['path'] = fullPath
      }
      router.replace({ name: REDIRECT_NAME, params, query }).then(() => resolve(true))
    })
  }
  return redo
}
